package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {

    public Socket socket = null;

    public TcpEchoClient(String ServerIp,int port) throws IOException {
        socket = new Socket(ServerIp,port);
    }
    public void start() throws IOException {
        //
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端启动");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            PrintWriter printWriter = new PrintWriter(outputStream);
            Scanner scannerFromSocket = new Scanner(inputStream);
            while (true){
                //1.从键盘上读取用户输入的内容
                System.out.println("->");
                String request = scanner.next();
                //这里的发送带有换行的
                //2.把读取的内容构造成请求发给服务器
                printWriter.println(request);
                //3.读取服务器返回的响应内容
                  String response = scannerFromSocket.next();//从网卡中读取返回的响应内容
                //4.将响应内容打印到屏幕上
                System.out.printf("rep:%s resp:%s\n",request,response);

            }} catch (IOException e) {
            e.printStackTrace();
        }finally {
            socket.close();
        }

    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }

}
